// 引入axios
import axios from "axios";
// 引入qs模块，对数据进行序列化
import QS from "qs";
// 引入message模块，toast提示
import { ElMessage as message } from "element-plus";
// 引入storage模块，操作token
import { session } from "@/utils/storage";

// 请求超时时间
axios.defaults.timeout = 1000 * 10;
axios.defaults.baseURL =
  import.meta.env.VITE_ENV === "development" ? "/api" : "./";

// 请求拦截器
axios.interceptors.request.use(
  (config) => {
    if (!config) {
      config = {};
    }
    if (!config.headers) {
      config.headers = {};
    }
    if (!config.method) {
      config.method = "GET";
    }
    const token = session.get("token");
    token && (config.headers.Authorization = token);
    if (config.method.toUpperCase() === "POST") {
      config.headers["Content-Type"] = "application/json;charset=utf-8";
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);
// 响应拦截器
axios.interceptors.response.use(
  (response) => {
    if (response.status === 200) {
      return Promise.resolve(response);
    } else {
      return Promise.reject(response);
    }
  },
  // 服务器状态码不是200的情况
  (error) => {
    if (error.response.status) {
      switch (error.response.status) {
        case 500:
          message.error("网错错误，请稍后再试！");
          break;
        case 404:
          message.error("网错错误，请稍后再试！");
          break;
        // 其他错误，直接抛出错误提示
        default:
          message.error(error.response.data.message);
      }
      return Promise.reject(error.response);
    }
  }
);

export function get(url: string, params: any) {
  return new Promise((resolve, reject) => {
    axios
      .get(url, {
        params: params,
      })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}

export function post(url: string, params: any) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, params)
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}

export function postQs(url: string, params: any) {
  return new Promise((resolve, reject) => {
    axios
      .post(url, QS.stringify(params))
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}

export function getDynamicynamic(url: string, params: any) {
  return new Promise((resolve, reject) => {
    const completeUrl = `${url}/${params}`;
    axios
      .get(completeUrl, {})
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err.data);
      });
  });
}
